//
//  PhotoBrowserCell.swift
//  01- 搭建框架
//
//  Created by apple on 15/10/28.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

// 1 定义协议, 照片查看 cell  代理
protocol PhotoBrowserCellDelegate: NSObjectProtocol {

    // 点击图像视图
    func photoBrowserCellDidClickImage()
}
class PhotoBrowserCell: UICollectionViewCell {
    
    // 2 定义代理
    weak var photoDlegate: PhotoBrowserCellDelegate?
    
    /// MARK: - 监听方法
    @objc private func tapImage() {
        
        //print("关闭")
        photoDlegate?.photoBrowserCellDidClickImage()
    }
    
    // 设置图像
    var imageURL: NSURL? {
        didSet {
            
            guard let url = imageURL else {
                return
            }
            
            // 0> 重置滚动视图
            resetScrollView()
            // 1> 从磁盘加载缩略图的图像
            let placeholderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url.absoluteString)
//            imageViwe.image = placeholder
//            // 2> 设置大小
//            imageViwe.sizeToFit()
//            // 3> 设置中心点
//            imageViwe.center = scrollView.center
            setPlaceHolder(placeholderImage)
            // 异步加载大图
            imageViwe.sd_setImageWithURL(middleUrl(url),
                placeholderImage: nil,
                options: [SDWebImageOptions.RefreshCached, SDWebImageOptions.RetryFailed],
                progress: { (current, total) -> Void in
                    //
//                    print(NSThread.currentThread())
//                    print("\(current)\(total)")
                    // 更新进度
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHolder.progress = CGFloat(current) / CGFloat(total)
                    })

                }) { (image, _, _, _) -> Void in
                    // 隐藏占位图像
                    self.placeHolder.hidden = true
                    // 设置图像视图的位置
                    self.setPositon(image)
                               }
//            imageViwe.sd_setImageWithURL(middleUrl(url)) { (image, _, _, _) in
//                self.setPositon(image)
//                
//            }
        }
    }
    
    /// MARK: - 设置占位图像的内容
    private func setPlaceHolder(image: UIImage?) {
        
        placeHolder.hidden = false
        placeHolder.image = image
        placeHolder.sizeToFit()
        placeHolder.center = scrollView.center
    
    }
    // 重置滚动视图
    private func resetScrollView() {
        
        imageViwe.transform = CGAffineTransformIdentity
        
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        scrollView.contentSize = CGSizeZero
        
    }
    
    // 设置 iamgeView 的位置
    private func setPositon(image: UIImage) {
        
        // 自动设置大小
        let size = self.displaySize(image)
        
        // 判断图片的高度
        if size.height < scrollView.bounds.height {
            
            // 上下局中显示
            let y = (scrollView.bounds.height - size.height) * 0.5
            imageViwe.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
            
        } else {
            imageViwe.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentSize = size
        }
        
    }
    
    // 根据 scrollView 的宽度计算等比例缩放之后的图片尺寸
    private func displaySize(image: UIImage) -> CGSize {
    
        let w = scrollView.bounds.width
        let h = image.size.height * w / image.size.width
        
        return CGSize(width: w, height: h)
    }
    
    // 创建大图的URL
    private func middleUrl(url: NSURL) -> NSURL {
    
        var urlString = url.absoluteString
        urlString = urlString.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString)!
    }
    
    /// MAKE: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// MARK: - 设置界面
    private func setupUI() {

        // 1. 添加控件
        contentView.addSubview(scrollView)
        scrollView.addSubview(imageViwe)
        scrollView.addSubview(placeHolder)
        
        // 2. 自动布局
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        
        // 3. 设置缩放
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2.0
        
        // 4. 增加手势识别
        let tap = UITapGestureRecognizer(target: self, action: "tapImage")
        imageViwe.userInteractionEnabled = true
        imageViwe.addGestureRecognizer(tap)
}
    
    // 懒加载控件
    lazy var scrollView: UIScrollView = UIScrollView()
    lazy var imageViwe: UIImageView = UIImageView()
    //添加占位图像
    private lazy var placeHolder: ProgressImageView = ProgressImageView()
}


/// MARK: - UIScrollViewDelegate
extension PhotoBrowserCell:UIScrollViewDelegate {

    // 返回缩放的视图
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        
        return imageViwe
    }
    
    // 缩放后才会被调用
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        
        //print("缩放后才会被调用")
        var offsetY = (scrollView.bounds.height - view!.frame.height) * 0.5
        var offsetX = (scrollView.bounds.width - view!.frame.width) * 0.5
        
        offsetY = offsetY < 0 ? 0: offsetY
        offsetX = offsetX < 0 ? 0: offsetX
        
        scrollView.contentInset = UIEdgeInsets(top: offsetY, left: offsetX, bottom: 0, right: 0)
        
    }
    
    // 只要缩放就会被调用
    func scrollViewDidZoom(scrollView: UIScrollView) {
        //print("只要缩放就会被调用")
    }
}
